<template>
  <div class="main-container">
    <!-- 顶部导航 -->
    <nav-header ref="nav"></nav-header>
    <div class="content-container" ref="content">
      <!-- 公告提示 -->
      <tip-text ref="tip"></tip-text>
      <!-- 店铺信息 -->
      <shop-info ref="shop"></shop-info>

      <!-- 商品联动列表 -->
      <product-list
        @cancel-fixed="cancelFixed"
        :class="{ fixed: isFixed }"
      ></product-list>
      <!-- 购物车列表 -->
      <product-car ref="productCarList"></product-car>
      <!-- 下单悬浮窗 -->
      <order-bar @show-car-list='showCarList'></order-bar>
    </div>
  </div>
</template>

<script>
import NavHeader from "../components/NavHeader.vue";
import TipText from "../components/TipText.vue";
import ShopInfo from "../components/ShopInfo.vue";
import ProductList from "../components/ProductList.vue";
import ProductCar from "../components/ProductsCar.vue";
import OrderBar from "../components/OrderBar.vue";

export default {
  components: {
    NavHeader,
    TipText,
    ShopInfo,
    ProductList,
    ProductCar,
    OrderBar,
  },
  data() {
    return {
      isFixed: false, // 是否固定列表
    };
  },
  mounted() {
    setTimeout(() => {
      this.listenScroll();
    }, 0);
  },
  methods: {
    // 监听scroll事件
    listenScroll() {
      const contentRef = this.$refs.content;
      contentRef.addEventListener("scroll", this.scrollCallBack);
    },
		scrollCallBack(e) {
			if (e.target.scrollTop > this.getFixedHeight()) {
          if (!this.isFixed) {
            // this.isFixed = true;
						this.setFixed();
          }
        }
		},
    // 取消列表固定
    cancelFixed() {
      this.isFixed = false;
      this.$nextTick(() => {
        const contentRef = this.$refs.content;
        contentRef.scrollTop = this.getFixedHeight();
      });
    },
		setFixed() {
			this.isFixed = true;
		},
		// 获取需要固定时滚动的高度
    getFixedHeight() {
      const tipHeight = this.$refs.tip.$el.offsetHeight ?? 0; // 兼容：提示信息隐藏时高度为0
      const shopHeight = this.$refs.shop.$el.offsetHeight;
      return tipHeight + shopHeight;
    },
		showCarList() {
			// 购物车无商品时  不显示购物车列表
			if(!this.$store.state.selectedProducts.length) {
				return
			}
			this.$refs.productCarList.showCarList();
		}
  },
	destroyed() {
		// 组件销毁时  移除事件
		const contentRef = this.$refs.content;
		contentRef.removeEventListener("scroll", this.scrollCallBack);
	},
};
</script>

<style scoped>
.main-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  font-size: 0.14rem;
}
.content-container {
  flex: 1;
  overflow-y: auto;
}
.fixed {
  position: fixed;
  left: 0;
  top: 0.48rem;
  right: 0;
  bottom: 0;
  overflow-y: auto;
}
</style>
